#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <cctype>
#include <algorithm> // 添加 transform 所需的头文件
using namespace std;

// 辅助函数：清理单词中的标点并转为小写
string processWord(string word) {
    string cleaned;
    for (char &c : word) {
        if (isalpha(static_cast<unsigned char>(c))) { // 仅保留字母
            cleaned += tolower(static_cast<unsigned char>(c)); // 转小写
        }
    }
    return cleaned;
}

void test() {
    map<string, int> words;

    ifstream ifs("The_Holy_Bible.txt");
    if (!ifs.is_open()) { // 检查文件是否成功打开
        cerr << "Error opening input file!" << endl;
        return;
    }

    string line;
    while (getline(ifs, line)) {
        istringstream iss(line);
        string rawWord;
        while (iss >> rawWord) {
            string cleanedWord = processWord(rawWord);
            if (!cleanedWord.empty()) { // 忽略空字符串（如纯标点符号）
                words[cleanedWord]++;   // 直接通过 [] 操作符统计词频
            }
        }
    }
    ifs.close();

    ofstream ofs("bible.txt");
    if (!ofs.is_open()) { // 检查输出文件是否成功打开
        cerr << "Error opening output file!" << endl;
        return;
    }

    for (const auto &entry : words) {
        ofs << entry.first << "\t" << entry.second << endl; // 添加分隔符
    }
    ofs.close();
}

int main(int argc, char *argv[]) {
    test();
    return 0;
}
